A complete answer which toggles the view visibility in onClick, also flips arrow upside down, and also moves other views up smoothly when hiding the component.
private fun toggleRecyclerViewVisibility(
recyclerView: RecyclerView,
container: FrameLayout,
arrow: ImageView
) {
//toggle arrow direction, also block user clicks until animation finishes.
arrow
.animate()
.rotation(
if (arrow.rotation == 0F)
180F
else 0F
)
.withStartAction { container.isClickable = false }
.withEndAction { container.isClickable = true }
.start()
//toggle recyclerview visibility with animation.
with(recyclerView) {
var cof = -1
var vis = View.GONE
var alph = 0F
if (visibility == View.GONE) {
cof = 0
vis = View.VISIBLE
alph = 1F
}
animate()
.translationY(height.toFloat() * cof)
.alpha(alph)
.withStartAction {//in case showing the recyclerview show it at the beginning.
if (vis == View.VISIBLE)
visibility = View.VISIBLE
}
.withEndAction {//in case hiding the recyclerview hide it at the end.
if (vis == View.GONE)
visibility = View.GONE
}
.start()
}
}
the views looks like this
<LinearLayout
android:id="@+id/subRootLinearView"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--other views-->
<LinearLayout
android:id="@+id/Container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/backgroundGray"
android:padding="16dp">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/awaitingConfirmation"
android:textColor="@color/colorText"
android:textSize="16sp" />
<ImageView
android:id="@+id/arrow_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:src="@drawable/ic_arrow" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>
</LinearLayout>
<!--other views-->
</LinearLayout>
then inside your code you add this line first, which solves animateLayoutChanges
not working in big nested views, which basically makes other views move up smoothly when hiding the recyclerview
subRootLinearView.layoutTransition.enableTransitionType(LayoutTransition.CHANGING)
also your parent linear layout should include this attribute
android:animateLayoutChanges="true"
then call the method with your views
toggleRecyclerViewVisibility(
recycler,
header,
arrowImageView
)